"""
权限服务层
负责权限检查和管理的业务逻辑
"""
from typing import List, Dict, Any, Optional
from bson import ObjectId  # pyright: ignore[reportMissingImports]
from app.models.user import UserRole
from app.enums.permission import (
    Permission,
    PERMISSION_MODULES,
    get_permission_description,
    get_all_permissions,
    get_permissions_by_module,
)
import logging

logger = logging.getLogger(__name__)

# 向后兼容：保留 Permissions 类，使用 Permission 枚举的值
class Permissions:
    """权限常量类（向后兼容）"""
    # 用户管理权限
    USER_CREATE = Permission.USER_CREATE.value
    USER_READ = Permission.USER_READ.value
    USER_UPDATE = Permission.USER_UPDATE.value
    USER_DELETE = Permission.USER_DELETE.value
    
    # 项目管理权限
    PROJECT_CREATE = Permission.PROJECT_CREATE.value
    PROJECT_READ = Permission.PROJECT_READ.value
    PROJECT_READ_ALL = Permission.PROJECT_READ_ALL.value
    PROJECT_UPDATE = Permission.PROJECT_UPDATE.value
    PROJECT_UPDATE_ALL = Permission.PROJECT_UPDATE_ALL.value
    PROJECT_DELETE = Permission.PROJECT_DELETE.value
    PROJECT_MANAGE_MEMBERS = Permission.PROJECT_MANAGE_MEMBERS.value
    PROJECT_ARCHIVE = Permission.PROJECT_ARCHIVE.value
    PROJECT_UNARCHIVE = Permission.PROJECT_UNARCHIVE.value
    PROJECT_STATS = Permission.PROJECT_STATS.value
    PROJECT_ANALYTICS = Permission.PROJECT_ANALYTICS.value
    PROJECT_ADD_MEMBER = Permission.PROJECT_ADD_MEMBER.value
    PROJECT_REMOVE_MEMBER = Permission.PROJECT_REMOVE_MEMBER.value
    PROJECT_UPDATE_MEMBER_ROLE = Permission.PROJECT_UPDATE_MEMBER_ROLE.value
    PROJECT_CHANGE_STATUS = Permission.PROJECT_CHANGE_STATUS.value
    PROJECT_CLOSE = Permission.PROJECT_CLOSE.value
    PROJECT_REOPEN = Permission.PROJECT_REOPEN.value
    PROJECT_CONFIGURE = Permission.PROJECT_CONFIGURE.value
    PROJECT_SETTINGS = Permission.PROJECT_SETTINGS.value
    PROJECT_EXPORT = Permission.PROJECT_EXPORT.value
    PROJECT_IMPORT = Permission.PROJECT_IMPORT.value
    PROJECT_TEMPLATE_CREATE = Permission.PROJECT_TEMPLATE_CREATE.value
    PROJECT_TEMPLATE_USE = Permission.PROJECT_TEMPLATE_USE.value
    
    # 任务管理权限
    TASK_CREATE = Permission.TASK_CREATE.value
    TASK_READ = Permission.TASK_READ.value
    TASK_READ_ALL = Permission.TASK_READ_ALL.value
    TASK_UPDATE = Permission.TASK_UPDATE.value
    TASK_DELETE = Permission.TASK_DELETE.value
    TASK_LOG_TIME = Permission.TASK_LOG_TIME.value
    TASK_ASSIGN = Permission.TASK_ASSIGN.value
    
    # 缺陷管理权限
    DEFECT_CREATE = Permission.DEFECT_CREATE.value
    DEFECT_READ = Permission.DEFECT_READ.value
    DEFECT_READ_ALL = Permission.DEFECT_READ_ALL.value
    DEFECT_UPDATE = Permission.DEFECT_UPDATE.value
    DEFECT_DELETE = Permission.DEFECT_DELETE.value
    DEFECT_ASSIGN = Permission.DEFECT_ASSIGN.value

    # 测试用例管理权限
    TEST_CASE_CREATE = Permission.TEST_CASE_CREATE.value
    TEST_CASE_READ = Permission.TEST_CASE_READ.value
    TEST_CASE_READ_ALL = Permission.TEST_CASE_READ_ALL.value
    TEST_CASE_UPDATE = Permission.TEST_CASE_UPDATE.value
    TEST_CASE_DELETE = Permission.TEST_CASE_DELETE.value
    TEST_CASE_ASSIGN = Permission.TEST_CASE_ASSIGN.value
    TEST_CASE_EXECUTE = Permission.TEST_CASE_EXECUTE.value

    # 需求管理权限
    REQUIREMENT_CREATE = Permission.REQUIREMENT_CREATE.value
    REQUIREMENT_READ = Permission.REQUIREMENT_READ.value
    REQUIREMENT_READ_ALL = Permission.REQUIREMENT_READ_ALL.value
    REQUIREMENT_UPDATE = Permission.REQUIREMENT_UPDATE.value
    REQUIREMENT_DELETE = Permission.REQUIREMENT_DELETE.value

    # 知识库权限
    DOC_CREATE = Permission.DOC_CREATE.value
    DOC_READ = Permission.DOC_READ.value
    DOC_UPDATE = Permission.DOC_UPDATE.value
    DOC_DELETE = Permission.DOC_DELETE.value
    
    # 系统管理权限
    SYSTEM_SETTINGS = Permission.SYSTEM_SETTINGS.value
    SYSTEM_LOGS = Permission.SYSTEM_LOGS.value
    SYSTEM_MANAGE = Permission.SYSTEM_MANAGE.value
    
    # 管理员权限
    ADMIN = Permission.ADMIN.value
    
    # 版本管理权限
    VERSION_CREATE = Permission.VERSION_CREATE.value
    VERSION_READ = Permission.VERSION_READ.value
    VERSION_READ_ALL = Permission.VERSION_READ_ALL.value
    VERSION_UPDATE = Permission.VERSION_UPDATE.value
    VERSION_DELETE = Permission.VERSION_DELETE.value
    VERSION_RELEASE = Permission.VERSION_RELEASE.value
    VERSION_ROLLBACK = Permission.VERSION_ROLLBACK.value
    
    # 版本审批权限
    VERSION_TRANSITION_REQUEST = Permission.VERSION_TRANSITION_REQUEST.value
    VERSION_TRANSITION_APPROVE = Permission.VERSION_TRANSITION_APPROVE.value
    VERSION_TRANSITION_READ = Permission.VERSION_TRANSITION_READ.value
    VERSION_TRANSITION_CANCEL = Permission.VERSION_TRANSITION_CANCEL.value
    VERSION_TRANSITION_REVOKE = Permission.VERSION_TRANSITION_REVOKE.value
    
    # 评论管理权限
    COMMENT_CREATE = Permission.COMMENT_CREATE.value
    COMMENT_READ = Permission.COMMENT_READ.value
    COMMENT_UPDATE = Permission.COMMENT_UPDATE.value
    COMMENT_DELETE = Permission.COMMENT_DELETE.value
    
    # 角色管理权限
    ROLE_CREATE = Permission.ROLE_CREATE.value
    ROLE_READ = Permission.ROLE_READ.value
    ROLE_UPDATE = Permission.ROLE_UPDATE.value
    ROLE_DELETE = Permission.ROLE_DELETE.value
    ROLE_MANAGE = Permission.ROLE_MANAGE.value

# 角色默认权限映射
ROLE_PERMISSIONS = {
    UserRole.ADMIN: [
        # 管理员拥有所有权限
        "*"
    ],
    UserRole.USER: [
        # 用户管理
        Permissions.USER_READ,
        
        # 项目管理（基础查看权限）
        Permissions.PROJECT_READ,
        
        # 任务管理（基础查看权限）
        Permissions.TASK_READ,
        
        # 缺陷管理（完整权限）
        Permissions.DEFECT_CREATE,
        Permissions.DEFECT_READ,
        Permissions.DEFECT_UPDATE,
        Permissions.DEFECT_DELETE,
        
        # 需求管理（基础查看权限）
        Permissions.REQUIREMENT_READ,
        
        # 知识库（创建、查看、更新权限）
        Permissions.DOC_CREATE,
        Permissions.DOC_READ,
        Permissions.DOC_UPDATE,
        
        # 版本管理（基础查看权限）
        Permissions.VERSION_READ,
        
        # 评论管理
        Permissions.COMMENT_CREATE,
        Permissions.COMMENT_READ,
        Permissions.COMMENT_UPDATE,
    ],
    UserRole.PRODUCT_MANAGER: [
        # 用户管理
        Permissions.USER_READ,

        # 项目管理
        Permissions.PROJECT_CREATE,
        Permissions.PROJECT_READ,
        Permissions.PROJECT_READ_ALL,
        Permissions.PROJECT_UPDATE,
        Permissions.PROJECT_MANAGE_MEMBERS,
        Permissions.PROJECT_STATS,
        Permissions.PROJECT_ANALYTICS,
        Permissions.PROJECT_EXPORT,  # 产品经理可以导出项目数据
        Permissions.PROJECT_TEMPLATE_USE,

        # 任务管理
        Permissions.TASK_CREATE,
        Permissions.TASK_READ,
        Permissions.TASK_UPDATE,
        Permissions.TASK_ASSIGN,
        Permissions.TASK_DELETE,  # 产品经理可以删除任务

        # 缺陷管理
        Permissions.DEFECT_CREATE,
        Permissions.DEFECT_READ,
        Permissions.DEFECT_READ_ALL,  # 产品经理可以查看所有缺陷
        Permissions.DEFECT_UPDATE,
        Permissions.DEFECT_DELETE,
        Permissions.DEFECT_ASSIGN,

        # 测试用例管理（产品经理需要查看测试用例）
        Permissions.TEST_CASE_READ,
        Permissions.TEST_CASE_READ_ALL,

        # 需求管理
        Permissions.REQUIREMENT_CREATE,
        Permissions.REQUIREMENT_READ,
        Permissions.REQUIREMENT_READ_ALL,  # 产品经理可以查看所有需求
        Permissions.REQUIREMENT_UPDATE,
        Permissions.REQUIREMENT_DELETE,  # 产品经理可以删除需求

        # 知识库
        Permissions.DOC_CREATE,
        Permissions.DOC_READ,
        Permissions.DOC_UPDATE,
        Permissions.DOC_DELETE,  # 产品经理可以删除文档

        # 版本管理
        Permissions.VERSION_READ,
        Permissions.VERSION_READ_ALL,  # 产品经理可以查看所有版本
        Permissions.VERSION_TRANSITION_REQUEST,
        Permissions.VERSION_TRANSITION_READ,

        # 评论管理
        Permissions.COMMENT_CREATE,
        Permissions.COMMENT_READ,
        Permissions.COMMENT_UPDATE,
        Permissions.COMMENT_DELETE,  # 产品经理可以删除评论
    ],
    UserRole.OPERATIONS_SPECIALIST: [
        # 用户管理
        Permissions.USER_READ,

        # 项目管理
        Permissions.PROJECT_READ,
        Permissions.PROJECT_STATS,
        Permissions.PROJECT_ANALYTICS,
        Permissions.PROJECT_EXPORT,

        # 任务管理
        Permissions.TASK_CREATE,  # 运营专员可以创建任务
        Permissions.TASK_READ,
        Permissions.TASK_UPDATE,
        Permissions.TASK_ASSIGN,  # 运营专员可以分配任务

        # 缺陷管理
        Permissions.DEFECT_CREATE,
        Permissions.DEFECT_READ,
        Permissions.DEFECT_UPDATE,
        Permissions.DEFECT_DELETE,
        Permissions.DEFECT_ASSIGN,

        # 需求管理
        Permissions.REQUIREMENT_READ,
        Permissions.REQUIREMENT_UPDATE,

        # 版本管理
        Permissions.VERSION_READ,
        Permissions.VERSION_UPDATE,
        Permissions.VERSION_RELEASE,

        # 知识库（运营专员拥有完整权限）
        Permissions.DOC_CREATE,
        Permissions.DOC_READ,
        Permissions.DOC_UPDATE,
        Permissions.DOC_DELETE,  # 运营专员可以删除文档

        # 评论管理
        Permissions.COMMENT_CREATE,
        Permissions.COMMENT_READ,
        Permissions.COMMENT_UPDATE,
        Permissions.COMMENT_DELETE,  # 运营专员可以删除评论
    ],
    UserRole.OPS_ENGINEER: [
        # 用户管理
        Permissions.USER_READ,

        # 项目管理
        Permissions.PROJECT_READ,
        Permissions.PROJECT_STATS,
        Permissions.PROJECT_EXPORT,  # 运维工程师可以导出项目数据

        # 任务管理
        Permissions.TASK_CREATE,  # 运维工程师可以创建任务
        Permissions.TASK_READ,
        Permissions.TASK_UPDATE,
        Permissions.TASK_ASSIGN,  # 运维工程师可以分配任务

        # 缺陷管理
        Permissions.DEFECT_CREATE,
        Permissions.DEFECT_READ,
        Permissions.DEFECT_UPDATE,
        Permissions.DEFECT_DELETE,
        Permissions.DEFECT_ASSIGN,

        # 版本管理
        Permissions.VERSION_READ,
        Permissions.VERSION_UPDATE,
        Permissions.VERSION_RELEASE,
        Permissions.VERSION_ROLLBACK,

        # 知识库（运维工程师可以创建、查看、更新文档）
        Permissions.DOC_CREATE,
        Permissions.DOC_READ,
        Permissions.DOC_UPDATE,

        # 评论管理
        Permissions.COMMENT_CREATE,
        Permissions.COMMENT_READ,
        Permissions.COMMENT_UPDATE,  # 运维工程师可以更新评论
    ],
    UserRole.PROJECT_MANAGER: [
        # 用户管理
        Permissions.USER_READ,
        
        # 项目管理
        Permissions.PROJECT_CREATE,
        Permissions.PROJECT_READ,
        Permissions.PROJECT_READ_ALL,
        Permissions.PROJECT_UPDATE,
        Permissions.PROJECT_UPDATE_ALL,
        Permissions.PROJECT_MANAGE_MEMBERS,
        
        # 项目归档权限
        Permissions.PROJECT_ARCHIVE,
        Permissions.PROJECT_UNARCHIVE,
        
        # 项目统计和分析权限
        Permissions.PROJECT_STATS,
        Permissions.PROJECT_ANALYTICS,
        
        # 项目成员管理细分权限
        Permissions.PROJECT_ADD_MEMBER,
        Permissions.PROJECT_REMOVE_MEMBER,
        Permissions.PROJECT_UPDATE_MEMBER_ROLE,
        
        # 项目状态管理权限
        Permissions.PROJECT_CHANGE_STATUS,
        Permissions.PROJECT_CLOSE,
        Permissions.PROJECT_REOPEN,
        
        # 项目配置权限
        Permissions.PROJECT_CONFIGURE,
        Permissions.PROJECT_SETTINGS,
        
        # 项目导入导出权限
        Permissions.PROJECT_EXPORT,
        Permissions.PROJECT_IMPORT,
        
        # 项目模板权限
        Permissions.PROJECT_TEMPLATE_CREATE,
        Permissions.PROJECT_TEMPLATE_USE,
        
        # 任务管理
        Permissions.TASK_CREATE,
        Permissions.TASK_READ,
        Permissions.TASK_READ_ALL,
        Permissions.TASK_UPDATE,
        Permissions.TASK_DELETE,
        Permissions.TASK_ASSIGN,

        # 缺陷管理
        Permissions.DEFECT_CREATE,
        Permissions.DEFECT_READ,
        Permissions.DEFECT_READ_ALL,
        Permissions.DEFECT_UPDATE,
        Permissions.DEFECT_DELETE,
        Permissions.DEFECT_ASSIGN,
        
        # 测试用例管理
        Permissions.TEST_CASE_CREATE,
        Permissions.TEST_CASE_READ,
        Permissions.TEST_CASE_READ_ALL,
        Permissions.TEST_CASE_UPDATE,
        Permissions.TEST_CASE_DELETE,
        Permissions.TEST_CASE_ASSIGN,
        Permissions.TEST_CASE_EXECUTE,
        
        # 需求管理
        Permissions.REQUIREMENT_CREATE,
        Permissions.REQUIREMENT_READ,
        Permissions.REQUIREMENT_READ_ALL,
        Permissions.REQUIREMENT_UPDATE,
        Permissions.REQUIREMENT_DELETE,
        
        # 知识库
        Permissions.DOC_CREATE,
        Permissions.DOC_READ,
        Permissions.DOC_UPDATE,
        Permissions.DOC_DELETE,
        
        # 系统管理权限
        Permissions.SYSTEM_MANAGE,
        
        # 版本管理
        Permissions.VERSION_CREATE,
        Permissions.VERSION_READ,
        Permissions.VERSION_READ_ALL,
        Permissions.VERSION_UPDATE,
        Permissions.VERSION_DELETE,
        Permissions.VERSION_RELEASE,
        Permissions.VERSION_ROLLBACK,
        
        # 版本审批权限（项目经理拥有全部审批权限）
        Permissions.VERSION_TRANSITION_REQUEST,
        Permissions.VERSION_TRANSITION_APPROVE,
        Permissions.VERSION_TRANSITION_READ,
        Permissions.VERSION_TRANSITION_CANCEL,
        
        # 评论管理
        Permissions.COMMENT_CREATE,
        Permissions.COMMENT_READ,
        Permissions.COMMENT_UPDATE,
        Permissions.COMMENT_DELETE,
    ],
    UserRole.DEVELOPER: [
        # 用户管理
        Permissions.USER_READ,
        
        # 项目管理
        Permissions.PROJECT_READ,
        
        # 项目统计权限（开发者可查看项目统计）
        Permissions.PROJECT_STATS,
        
        # 项目导出权限（开发者可导出项目数据）
        Permissions.PROJECT_EXPORT,
        
        # 项目模板使用权限
        Permissions.PROJECT_TEMPLATE_USE,
        
        # 任务管理
        Permissions.TASK_CREATE,  # 开发者可以创建任务
        Permissions.TASK_READ,
        Permissions.TASK_UPDATE,
        Permissions.TASK_ASSIGN,  # 开发者可以分配任务
        Permissions.TASK_DELETE,  # 开发者可以删除自己创建的任务
        
        # 缺陷管理
        Permissions.DEFECT_CREATE,
        Permissions.DEFECT_READ,
        Permissions.DEFECT_UPDATE,
        Permissions.DEFECT_DELETE,
        Permissions.DEFECT_ASSIGN,
        
        # 需求管理
        Permissions.REQUIREMENT_CREATE,
        Permissions.REQUIREMENT_READ,
        Permissions.REQUIREMENT_UPDATE,
        
        # 知识库（开发者拥有完整权限）
        Permissions.DOC_CREATE,
        Permissions.DOC_READ,
        Permissions.DOC_UPDATE,
        Permissions.DOC_DELETE,  # 开发者可以删除文档
        
        # 版本管理
        Permissions.VERSION_READ,
        Permissions.VERSION_UPDATE,
        Permissions.VERSION_CREATE,  # 开发者可以创建版本
        
        # 版本审批权限（开发者可以提交申请，不能审批）
        Permissions.VERSION_TRANSITION_REQUEST,
        Permissions.VERSION_TRANSITION_READ,
        Permissions.VERSION_TRANSITION_CANCEL,
        
        # 评论管理
        Permissions.COMMENT_CREATE,
        Permissions.COMMENT_READ,
        Permissions.COMMENT_UPDATE,
        Permissions.COMMENT_DELETE,
    ],
    UserRole.TESTER: [
        # 用户管理
        Permissions.USER_READ,
        
        # 项目管理
        Permissions.PROJECT_READ,
        
        # 项目统计权限（测试人员可查看项目统计）
        Permissions.PROJECT_STATS,
        
        # 项目导出权限（测试人员可导出测试数据）
        Permissions.PROJECT_EXPORT,
        
        # 任务管理
        Permissions.TASK_CREATE,  # 测试人员可以创建任务
        Permissions.TASK_READ,
        Permissions.TASK_UPDATE,  # 测试人员可以更新任务
        Permissions.TASK_ASSIGN,  # 测试人员可以分配任务
        
        # 缺陷管理
        Permissions.DEFECT_CREATE,
        Permissions.DEFECT_READ,
        Permissions.DEFECT_UPDATE,
        Permissions.DEFECT_DELETE,
        Permissions.DEFECT_ASSIGN,
        
        # 测试用例管理（测试人员有完整权限）
        Permissions.TEST_CASE_CREATE,
        Permissions.TEST_CASE_READ,
        Permissions.TEST_CASE_READ_ALL,
        Permissions.TEST_CASE_UPDATE,
        Permissions.TEST_CASE_DELETE,
        Permissions.TEST_CASE_ASSIGN,
        Permissions.TEST_CASE_EXECUTE,
        
        # 需求管理
        Permissions.REQUIREMENT_CREATE,
        Permissions.REQUIREMENT_READ,
        Permissions.REQUIREMENT_UPDATE,
        
        # 知识库（测试人员可以创建、查看、更新文档）
        Permissions.DOC_CREATE,
        Permissions.DOC_READ,
        Permissions.DOC_UPDATE,
        
        # 版本管理
        Permissions.VERSION_READ,
        Permissions.VERSION_UPDATE,
        
        # 版本审批权限（测试员可以提交申请，不能审批）
        Permissions.VERSION_TRANSITION_REQUEST,
        Permissions.VERSION_TRANSITION_READ,
        Permissions.VERSION_TRANSITION_CANCEL,
        
        # 评论管理
        Permissions.COMMENT_CREATE,
        Permissions.COMMENT_READ,
        Permissions.COMMENT_UPDATE,
        Permissions.COMMENT_DELETE,
    ],
    UserRole.VIEWER: [
        # 用户管理
        Permissions.USER_READ,
        
        # 项目管理
        Permissions.PROJECT_READ,
        
        # 项目统计权限（查看者可查看基本统计）
        Permissions.PROJECT_STATS,
        
        # 任务管理
        Permissions.TASK_READ,
        
        # 缺陷管理
        Permissions.DEFECT_READ,
        
        # 测试用例管理（查看者只能查看）
        Permissions.TEST_CASE_READ,
        
        # 需求管理
        Permissions.REQUIREMENT_READ,
        
        # 知识库
        Permissions.DOC_READ,
        
        # 版本管理
        Permissions.VERSION_READ,
        
        # 评论管理（查看者只能查看和创建评论）
        Permissions.COMMENT_CREATE,
        Permissions.COMMENT_READ,
    ],
    UserRole.OWNER: [
        # 拥有者拥有项目的所有权限
        Permissions.PROJECT_READ,
        Permissions.PROJECT_UPDATE,
        Permissions.PROJECT_DELETE,
        Permissions.PROJECT_MANAGE_MEMBERS,
        Permissions.PROJECT_ADD_MEMBER,
        Permissions.PROJECT_REMOVE_MEMBER,
        Permissions.PROJECT_UPDATE_MEMBER_ROLE,
        Permissions.PROJECT_ARCHIVE,
        Permissions.PROJECT_UNARCHIVE,
        Permissions.PROJECT_STATS,
        Permissions.PROJECT_ANALYTICS,
        Permissions.PROJECT_CHANGE_STATUS,
        Permissions.PROJECT_CLOSE,
        Permissions.PROJECT_REOPEN,
        Permissions.PROJECT_CONFIGURE,
        Permissions.PROJECT_SETTINGS,
        Permissions.PROJECT_EXPORT,
        Permissions.PROJECT_IMPORT,
        Permissions.PROJECT_TEMPLATE_CREATE,
        Permissions.PROJECT_TEMPLATE_USE,
        
        # 任务管理
        Permissions.TASK_CREATE,
        Permissions.TASK_READ,
        Permissions.TASK_READ_ALL,
        Permissions.TASK_UPDATE,
        Permissions.TASK_DELETE,
        Permissions.TASK_ASSIGN,
        Permissions.TASK_LOG_TIME,
        
        # 缺陷管理
        Permissions.DEFECT_CREATE,
        Permissions.DEFECT_READ,
        Permissions.DEFECT_READ_ALL,
        Permissions.DEFECT_UPDATE,
        Permissions.DEFECT_DELETE,
        Permissions.DEFECT_ASSIGN,
        
        # 测试用例管理
        Permissions.TEST_CASE_CREATE,
        Permissions.TEST_CASE_READ,
        Permissions.TEST_CASE_READ_ALL,
        Permissions.TEST_CASE_UPDATE,
        Permissions.TEST_CASE_DELETE,
        Permissions.TEST_CASE_ASSIGN,
        Permissions.TEST_CASE_EXECUTE,
        
        # 需求管理
        Permissions.REQUIREMENT_CREATE,
        Permissions.REQUIREMENT_READ,
        Permissions.REQUIREMENT_READ_ALL,
        Permissions.REQUIREMENT_UPDATE,
        Permissions.REQUIREMENT_DELETE,
        
        # 知识库
        Permissions.DOC_CREATE,
        Permissions.DOC_READ,
        Permissions.DOC_UPDATE,
        Permissions.DOC_DELETE,
        
        # 版本管理
        Permissions.VERSION_CREATE,
        Permissions.VERSION_READ,
        Permissions.VERSION_READ_ALL,
        Permissions.VERSION_UPDATE,
        Permissions.VERSION_DELETE,
        Permissions.VERSION_RELEASE,
        Permissions.VERSION_ROLLBACK,
        
        # 版本审批
        Permissions.VERSION_TRANSITION_REQUEST,
        Permissions.VERSION_TRANSITION_APPROVE,
        Permissions.VERSION_TRANSITION_READ,
        Permissions.VERSION_TRANSITION_CANCEL,
        Permissions.VERSION_TRANSITION_REVOKE,
        
        # 评论管理
        Permissions.COMMENT_CREATE,
        Permissions.COMMENT_READ,
        Permissions.COMMENT_UPDATE,
        Permissions.COMMENT_DELETE,
    ],
}


class PermissionService:
    """权限服务类"""
    
    @staticmethod
    def has_permission(user: Dict[str, Any], permission: str) -> bool:
        """
        检查用户是否拥有指定权限
        
        Args:
            user: 用户信息字典，必须包含 permissions 和 roles 字段
            permission: 要检查的权限字符串
            
        Returns:
            bool: 如果用户拥有权限返回True，否则返回False
        """
        user_permissions = user.get("permissions", [])
        user_roles = user.get("roles", [])
        
        # 检查直接权限（包括通配符）
        if "*" in user_permissions or permission in user_permissions:
            logger.debug(f"User has permission: {permission}")
            return True
            
        # 以前的逻辑检查 user_roles 中的 "admin"，现在应该依赖 user_permissions 中的 "*"
        # 但为了兼容性，如果 user_roles 包含 "admin" 代码，也允许
        if "admin" in user_roles:
             return True
        
        logger.debug(f"User does not have permission: {permission}")
        return False
    
    @staticmethod
    def has_permissions(user: Dict[str, Any], permissions: List[str]) -> bool:
        """
        检查用户是否拥有所有指定权限（AND关系）
        
        Args:
            user: 用户信息字典
            permissions: 权限列表，用户必须拥有所有权限
            
        Returns:
            bool: 如果用户拥有所有权限返回True，否则返回False
        """
        if not permissions:
            return True
        
        # 管理员拥有所有权限（快速检查）
        user_roles = user.get("roles", [])
        user_permissions = user.get("permissions", [])
        if "admin" in user_roles or "*" in user_permissions:
            return True
        
        # 批量检查权限（优化性能）
        return all(PermissionService.has_permission(user, perm) for perm in permissions)
    
    @staticmethod
    def has_any_permission(user: Dict[str, Any], permissions: List[str]) -> bool:
        """
        检查用户是否拥有任意一个指定权限（OR关系）
        
        Args:
            user: 用户信息字典
            permissions: 权限列表，用户只需拥有其中一个权限
            
        Returns:
            bool: 如果用户拥有任一权限返回True，否则返回False
        """
        if not permissions:
            return True
        
        # 管理员拥有所有权限（快速检查）
        user_roles = user.get("roles", [])
        user_permissions = user.get("permissions", [])
        if "admin" in user_roles or "*" in user_permissions:
            return True
        
        # 检查是否有任一权限
        return any(PermissionService.has_permission(user, perm) for perm in permissions)
    
    @staticmethod
    def has_roles(user: Dict[str, Any], roles: List[str]) -> bool:
        """
        检查用户是否拥有任一指定角色（OR关系）
        
        Args:
            user: 用户信息字典
            roles: 角色列表，用户只需拥有其中一个角色
            
        Returns:
            bool: 如果用户拥有任一角色返回True，否则返回False
        """
        if not roles:
            return True
        
        user_roles = set(user.get("roles", []))
        
        # 管理员拥有所有角色权限
        if "admin" in user_roles:
            return True
        
        # 检查是否有任一角色（使用集合交集提高性能）
        required_roles = set(roles)
        # 兼容性处理：同时支持 "manager" 和 "project_manager"
        if "manager" in required_roles:
            required_roles.add("project_manager")
        if "project_manager" in required_roles:
            required_roles.add("manager")
        
        return bool(user_roles & required_roles)
    
    @staticmethod
    def has_all_roles(user: Dict[str, Any], roles: List[str]) -> bool:
        """
        检查用户是否拥有所有指定角色（AND关系）
        
        Args:
            user: 用户信息字典
            roles: 角色列表，用户必须拥有所有角色
            
        Returns:
            bool: 如果用户拥有所有角色返回True，否则返回False
        """
        if not roles:
            return True
        
        user_roles = set(user.get("roles", []))
        
        # 管理员拥有所有角色权限
        if "admin" in user_roles:
            return True
        
        required_roles = set(roles)
        # 兼容性处理
        if "manager" in required_roles:
            required_roles.add("project_manager")
        if "project_manager" in required_roles:
            required_roles.add("manager")
        
        return required_roles.issubset(user_roles)
    
    @staticmethod
    def get_permissions_for_role(role: UserRole) -> List[str]:
        """获取角色对应的权限列表"""
        return ROLE_PERMISSIONS.get(role, [])
    
    @staticmethod
    async def calculate_user_permissions(user: Dict[str, Any], db=None) -> List[str]:
        """
        计算用户的所有权限（包括直接权限和角色权限）
        """
        user_permissions = set(user.get("permissions", []))
        
        # 检查是否有 "*" (管理员)
        if "*" in user_permissions:
            return ["*"]
            
        # 获取系统角色ID列表
        system_role_ids = user.get("system_roles", [])
        
        if not system_role_ids or db is None:
            return sorted(list(user_permissions))
            
        # 从数据库获取角色信息
        try:
            role_oids = []
            for rid in system_role_ids:
                if ObjectId.is_valid(rid):
                    role_oids.append(ObjectId(rid))
            
            if role_oids:
                roles = await db.roles.find({"_id": {"$in": role_oids}}).to_list(None)
                for role in roles:
                    # 检查管理员角色
                    if role.get("code") == "admin":
                        return ["*"]
                    
                    perms = role.get("permissions", [])
                    if "*" in perms:
                        return ["*"]
                    user_permissions.update(perms)
        except Exception as e:
            logger.error(f"Error calculating user permissions: {str(e)}")
            
        return sorted(list(user_permissions))
    
    @staticmethod
    async def is_project_member(project_id: str, user_id: str, db) -> bool:
        """
        检查用户是否为项目成员
        
        Args:
            project_id: 项目ID
            user_id: 用户ID
            db: 数据库连接
            
        Returns:
            bool: 如果用户是项目成员返回True，否则返回False
        """
        try:
            # 验证ObjectId格式
            if not ObjectId.is_valid(project_id):
                return False
            
            project_oid = ObjectId(project_id)
            
            # 从数据库查询项目成员关系
            project = await db.projects.find_one({"_id": project_oid})
            
            if not project:
                return False
            
            # 检查是否为项目创建者
            if project.get("created_by") == user_id or str(project.get("created_by")) == user_id:
                return True
            
            # 检查是否为项目成员
            members = project.get("members", [])
            for member in members:
                member_user_id = member.get("user_id")
                if member_user_id and (str(member_user_id) == user_id or member_user_id == user_id):
                    return True
            
            return False
        except Exception as e:
            logger.error(f"Error checking project membership: {str(e)}")
            return False
    
    @staticmethod
    async def check_project_access(
        project_id: str, 
        user: Dict[str, Any], 
        db,
        required_permission: Optional[str] = None
    ) -> bool:
        """
        检查用户是否有项目访问权限
        
        Args:
            project_id: 项目ID
            user: 用户信息字典
            db: 数据库连接
            required_permission: 需要的权限（可选）
            
        Returns:
            bool: 如果用户有权限返回True，否则返回False
        """
        try:
            user_id = user.get("user_id")
            user_roles = user.get("roles", [])
            user_permissions = user.get("permissions", [])
            
            # 管理员拥有所有权限
            if "admin" in user_roles or "*" in user_permissions:
                return True
            
            # 验证ObjectId格式
            if not ObjectId.is_valid(project_id):
                return False
            
            project_oid = ObjectId(project_id)
            project = await db.projects.find_one({"_id": project_oid})
            
            if not project:
                return False
            
            # 检查是否为项目创建者
            if project.get("created_by") == user_id or str(project.get("created_by")) == user_id:
                return True
            
            # 检查是否为公开项目
            if project.get("is_public", False):
                # 公开项目所有用户都可以访问
                return True
            
            # 检查是否为项目成员
            is_member = await PermissionService.is_project_member(project_id, user_id, db)
            if not is_member:
                return False
            
            # 如果指定了所需权限，使用项目成员权限检查（而不是全局权限）
            if required_permission:
                return await PermissionService.check_project_member_permission(
                    project_id, user, db, required_permission
                )
            
            return True
        except Exception as e:
            logger.error(f"Error checking project access: {str(e)}")
            return False
    
    @staticmethod
    async def check_project_member_permission(
        project_id: str,
        user: Dict[str, Any],
        db,
        required_permission: str
    ) -> bool:
        """
        检查项目成员是否拥有指定权限
        
        Args:
            project_id: 项目ID
            user: 用户信息字典
            db: 数据库连接
            required_permission: 需要的权限（如 requirement:read, task:create 等）
            
        Returns:
            bool: 如果用户有权限返回True，否则返回False
        """
        try:
            user_id = user.get("user_id")
            user_permissions = user.get("permissions", [])
            user_roles = user.get("roles", [])
            
            # 管理员拥有所有权限
            if "admin" in user_roles or "*" in user_permissions:
                return True
            
            # 验证ObjectId格式
            if not ObjectId.is_valid(project_id):
                return False
            
            project_oid = ObjectId(project_id)
            project = await db.projects.find_one({"_id": project_oid})
            
            if not project:
                return False
            
            # 检查是否为项目创建者（拥有所有权限）
            project_created_by = project.get("created_by")
            if project_created_by:
                if str(project_created_by) == user_id or project_created_by == user_id:
                    return True
            
            # 检查项目成员权限
            user_object_id = None
            if user_id and ObjectId.is_valid(user_id):
                user_object_id = ObjectId(user_id)
            
            if user_object_id:
                members = project.get("members", [])
                for member in members:
                    member_user_id = member.get("user_id")
                    if member_user_id == user_object_id or str(member_user_id) == user_id:
                        # 获取成员的项目权限列表
                        member_permissions = member.get("permissions", [])
                        
                        # 检查是否有通配符权限
                        if "*" in member_permissions:
                            return True
                        
                        # 检查是否有具体权限
                        if required_permission in member_permissions:
                            return True
                        
                        # 检查是否有模块级别的管理权限（如 requirement:manage 表示所有需求权限）
                        module = required_permission.split(":")[0] if ":" in required_permission else ""
                        if module and f"{module}:manage" in member_permissions:
                            return True
                        
                        # 检查是否有模块级别的所有权限（如 requirement:* 表示所有需求权限）
                        if module and f"{module}:*" in member_permissions:
                            return True
            
            # 如果不是项目成员，直接返回False（不再回退到全局权限）
            # 项目权限应该完全隔离，只有项目成员才能操作项目资源
            return False
        except Exception as e:
            logger.error(f"Error checking project member permission: {str(e)}")
            return False
    
    @staticmethod
    async def require_project_member_permission(
        project_id: str,
        user: Dict[str, Any],
        db,
        required_permission: str
    ) -> None:
        """
        要求项目成员拥有指定权限，否则抛出异常
        
        Args:
            project_id: 项目ID
            user: 用户信息字典
            db: 数据库连接
            required_permission: 需要的权限
            
        Raises:
            PermissionError: 如果用户没有权限
        """
        has_permission = await PermissionService.check_project_member_permission(
            project_id, user, db, required_permission
        )
        if not has_permission:
            permission_desc = get_permission_description(required_permission)
            raise PermissionError(f"权限不足: 需要 {permission_desc} ({required_permission}) 权限")
    
    @staticmethod
    async def check_project_member_permission(
        project_id: str,
        user: Dict[str, Any],
        db,
        required_permission: str
    ) -> bool:
        """
        检查项目成员是否拥有指定权限
        
        权限检查顺序：
        1. 管理员拥有所有权限
        2. 项目创建者拥有所有权限
        3. 检查项目成员权限（包括通配符、具体权限、模块级权限）
        4. 如果都不是项目成员，返回False（不再回退到全局权限）
        
        注意：项目权限应该完全隔离，只有项目成员才能操作项目资源。
        全局权限不能绕过项目权限检查。
        
        Args:
            project_id: 项目ID
            user: 用户信息字典
            db: 数据库连接
            required_permission: 需要的权限（如 requirement:read, task:create 等）
            
        Returns:
            bool: 如果用户有权限返回True，否则返回False
        """
        try:
            user_id = user.get("user_id")
            user_permissions = user.get("permissions", [])
            user_roles = user.get("roles", [])
            
            # 管理员拥有所有权限
            if "admin" in user_roles or "*" in user_permissions:
                return True
            
            # 验证ObjectId格式
            if not ObjectId.is_valid(project_id):
                return False
            
            project_oid = ObjectId(project_id)
            project = await db.projects.find_one({"_id": project_oid})
            
            if not project:
                return False
            
            # 检查是否为项目创建者（拥有所有权限）
            project_created_by = project.get("created_by")
            if project_created_by:
                created_by_str = str(project_created_by) if isinstance(project_created_by, ObjectId) else project_created_by
                if created_by_str == user_id or project_created_by == user_id:
                    return True
            
            # 检查项目成员权限
            user_object_id = None
            if user_id and ObjectId.is_valid(user_id):
                user_object_id = ObjectId(user_id)
            
            if user_object_id:
                members = project.get("members", [])
                for member in members:
                    member_user_id = member.get("user_id")
                    if member_user_id == user_object_id or (isinstance(member_user_id, ObjectId) and str(member_user_id) == user_id):
                        # 获取成员的项目权限列表
                        member_permissions = member.get("permissions", [])
                        
                        # 检查是否有通配符权限
                        if "*" in member_permissions:
                            return True
                        
                        # 检查是否有具体权限
                        if required_permission in member_permissions:
                            return True
                        
                        # 检查是否有模块级别的管理权限（如 requirement:manage 表示所有需求权限）
                        module = required_permission.split(":")[0] if ":" in required_permission else ""
                        if module and f"{module}:manage" in member_permissions:
                            return True
                        
                        # 检查是否有模块级别的所有权限（如 requirement:* 表示所有需求权限）
                        if module and f"{module}:*" in member_permissions:
                            return True
            
            # 如果不是项目成员，直接返回False（不再回退到全局权限）
            # 项目权限应该完全隔离，只有项目成员才能操作项目资源
            return False
        except Exception as e:
            logger.error(f"Error checking project member permission: {str(e)}")
            return False
    
    @staticmethod
    async def require_project_member_permission(
        project_id: str,
        user: Dict[str, Any],
        db,
        required_permission: str
    ) -> None:
        """
        要求项目成员拥有指定权限，否则抛出异常
        
        Args:
            project_id: 项目ID
            user: 用户信息字典
            db: 数据库连接
            required_permission: 需要的权限
            
        Raises:
            PermissionError: 如果用户没有权限
        """
        has_permission = await PermissionService.check_project_member_permission(
            project_id, user, db, required_permission
        )
        if not has_permission:
            permission_desc = get_permission_description(required_permission)
            raise PermissionError(f"权限不足: 需要 {permission_desc} ({required_permission}) 权限")
    
    @staticmethod
    def get_permission_description(permission: str) -> str:
        """
        获取权限的描述
        
        Args:
            permission: 权限字符串
            
        Returns:
            str: 权限描述，如果不存在返回权限字符串本身
        """
        return get_permission_description(permission)
    
    @staticmethod
    def get_permission_groups() -> Dict[str, List[Dict[str, str]]]:
        """
        获取权限分组
        使用权限枚举自动生成权限列表
        """
        groups = {}
        for module_code in PERMISSION_MODULES.keys():
            perms = get_permissions_by_module(module_code)
            groups[module_code] = [
                {"value": perm, "label": get_permission_description(perm)}
                for perm in sorted(perms)
            ]
        return groups
    
    @staticmethod
    def get_all_permissions() -> List[Dict[str, str]]:
        """
        获取所有权限列表（包含描述）
        
        Returns:
            List[Dict[str, str]]: 权限列表，每个元素包含 value 和 label
        """
        all_perms = get_all_permissions()
        return [
            {"value": perm, "label": desc}
            for perm, desc in sorted(all_perms.items())
        ]
    
    @staticmethod
    async def get_user_accessible_project_ids(
        user: Dict[str, Any],
        db,
        use_cache: bool = True
    ) -> Optional[List[ObjectId]]:
        """
        获取用户可访问的项目ID列表（带缓存）
        
        Args:
            user: 用户信息字典
            db: 数据库连接
            use_cache: 是否使用缓存（默认True）
            
        Returns:
            Optional[List[ObjectId]]: 项目ID列表
            - None: 管理员，可以访问所有项目
            - []: 空列表，用户没有任何项目权限
            - [ObjectId, ...]: 用户可访问的项目ID列表
        """
        user_id = user.get("user_id")
        user_roles = user.get("roles", [])
        user_permissions = user.get("permissions", [])
        
        # 管理员可以访问所有项目
        if "admin" in user_roles or "*" in user_permissions:
            return None  # None 表示可以访问所有项目
        
        # 检查是否有读取所有项目的权限
        if Permissions.PROJECT_READ_ALL in user_permissions:
            return None
        
        # 查询用户可访问的项目
        user_oid = ObjectId(user_id) if not isinstance(user_id, ObjectId) else user_id
        
        # 构建查询条件：公开项目、用户创建的项目、用户参与的项目
        project_query = {
            "$or": [
                {"is_public": True},
                {"created_by": user_oid},
                {"members.user_id": user_oid}
            ]
        }
        
        # 查询项目ID列表
        projects = await db.projects.find(project_query, {"_id": 1}).to_list(length=None)
        project_ids = [project["_id"] for project in projects]
        
        return project_ids
    
    @staticmethod
    async def build_data_permission_query(
        user: Dict[str, Any],
        db,
        module_type: str,
        base_query: Optional[Dict[str, Any]] = None,
        project_id_field: str = "project_id",
        assignee_id_field: Optional[str] = "assignee_id",
        reporter_id_field: Optional[str] = "reporter_id",
        creator_id_field: Optional[str] = "created_by",
        read_all_permission: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        构建数据权限查询条件（统一的数据权限过滤方法）
        
        Args:
            user: 用户信息字典
            db: 数据库连接
            module_type: 模块类型（如 "defect", "task", "requirement" 等）
            base_query: 基础查询条件（可选）
            project_id_field: 项目ID字段名（默认 "project_id"）
            assignee_id_field: 负责人ID字段名（默认 "assignee_id"，None表示不检查）
            reporter_id_field: 报告人ID字段名（默认 "reporter_id"，None表示不检查）
            creator_id_field: 创建人ID字段名（默认 "created_by"，None表示不检查）
            read_all_permission: 读取所有数据的权限（如 "defect:read_all"，None表示使用默认逻辑）
            
        Returns:
            Dict[str, Any]: 包含权限过滤的查询条件
        """
        if base_query is None:
            base_query = {}
        
        user_id = user.get("user_id")
        user_roles = user.get("roles", [])
        user_permissions = user.get("permissions", [])
        user_oid = ObjectId(user_id) if not isinstance(user_id, ObjectId) else user_id
        
        # 管理员或拥有读取所有数据权限的用户，不需要权限过滤
        if "admin" in user_roles or "*" in user_permissions:
            return base_query
        
        # 检查是否有读取所有数据的权限
        if read_all_permission and read_all_permission in user_permissions:
            return base_query
        
        # 如果基础查询中已经指定了项目ID，先验证项目访问权限
        if project_id_field in base_query:
            project_id_value = base_query[project_id_field]
            if isinstance(project_id_value, ObjectId) or (isinstance(project_id_value, str) and ObjectId.is_valid(project_id_value)):
                project_oid = project_id_value if isinstance(project_id_value, ObjectId) else ObjectId(project_id_value)
                has_access = await PermissionService.check_project_access(
                    str(project_oid),
                    user,
                    db
                )
                if not has_access:
                    # 用户没有权限访问该项目，返回空查询
                    return {"_id": {"$in": []}}
                # 用户有权限访问该项目，直接返回基础查询
                return base_query
        
        # 获取用户可访问的项目ID列表
        accessible_project_ids = await PermissionService.get_user_accessible_project_ids(user, db)
        
        # 管理员可以访问所有项目
        if accessible_project_ids is None:
            return base_query
        
        # 构建权限过滤条件
        permission_conditions = []
        
        # 添加项目权限条件
        if accessible_project_ids:
            permission_conditions.append({project_id_field: {"$in": accessible_project_ids}})
        
        # 添加负责人权限条件（如果基础查询中没有指定 assignee_id）
        # 如果基础查询中已经指定了 assignee_id，说明用户明确选择了筛选条件，不需要再添加权限条件
        if assignee_id_field and assignee_id_field not in base_query:
            permission_conditions.append({assignee_id_field: user_oid})
        
        # 添加报告人权限条件（如果基础查询中没有指定 reporter_id）
        if reporter_id_field and reporter_id_field not in base_query:
            permission_conditions.append({reporter_id_field: user_oid})
        
        # 添加创建人权限条件（如果基础查询中没有指定 creator_id）
        if creator_id_field and creator_id_field not in base_query:
            permission_conditions.append({creator_id_field: user_oid})
        
        # 如果没有权限条件，返回空查询
        if not permission_conditions:
            return {"_id": {"$in": []}}
        
        # 合并权限条件和基础查询
        if len(permission_conditions) == 1:
            permission_query = permission_conditions[0]
        else:
            permission_query = {"$or": permission_conditions}
        
        # 如果基础查询为空，直接返回权限查询
        if not base_query:
            return permission_query
        
        # 检查基础查询中是否已经有 _id 字段
        # 如果基础查询中已经有 _id 字段，需要特殊处理
        if "_id" in base_query:
            base_id_query = base_query.pop("_id")
            # 如果权限查询返回的是空查询（_id: {$in: []}），直接返回空查询
            if permission_query == {"_id": {"$in": []}}:
                return {"_id": {"$in": []}}
            
            # 检查权限查询中是否包含 _id 字段（可能在顶层，也可能在 $or 中）
            perm_id_query = None
            if "_id" in permission_query:
                perm_id_query = permission_query.pop("_id")
            elif "$or" in permission_query:
                # 检查 $or 中是否有 _id 字段
                or_conditions = permission_query["$or"]
                if isinstance(or_conditions, list):
                    # 使用列表推导式创建新列表，避免在迭代时修改列表
                    new_or_conditions = []
                    for condition in or_conditions:
                        if isinstance(condition, dict) and "_id" in condition:
                            # 如果 $or 中有 _id 条件，需要特殊处理
                            # 这种情况下，我们需要将 _id 条件提取出来，与 base_id_query 合并
                            if perm_id_query is None:
                                perm_id_query = condition.get("_id")
                            # 不添加到新列表中（移除这个条件）
                        else:
                            new_or_conditions.append(condition)
                    # 更新 $or 列表
                    if new_or_conditions:
                        permission_query["$or"] = new_or_conditions
                    else:
                        # 如果 $or 为空，移除 $or
                        permission_query.pop("$or")
            
            # 如果权限查询中也有 _id 字段，需要合并
            if perm_id_query is not None:
                # 合并两个 _id 查询：取交集
                if isinstance(base_id_query, dict) and "$in" in base_id_query:
                    base_ids = base_id_query["$in"]
                else:
                    base_ids = [base_id_query]
                if isinstance(perm_id_query, dict) and "$in" in perm_id_query:
                    perm_ids = perm_id_query["$in"]
                else:
                    perm_ids = [perm_id_query]
                # 取交集
                if isinstance(base_ids, list) and isinstance(perm_ids, list):
                    # 确保所有ID都是ObjectId类型
                    try:
                        base_ids_oids = [ObjectId(bid) if not isinstance(bid, ObjectId) and ObjectId.is_valid(str(bid)) else bid for bid in base_ids]
                        perm_ids_oids = [ObjectId(pid) if not isinstance(pid, ObjectId) and ObjectId.is_valid(str(pid)) else pid for pid in perm_ids]
                        common_ids = list(set(base_ids_oids) & set(perm_ids_oids))
                        if not common_ids:
                            return {"_id": {"$in": []}}
                        base_query["_id"] = {"$in": common_ids}
                    except Exception:
                        # 如果转换失败，返回空查询
                        return {"_id": {"$in": []}}
                else:
                    # 如果类型不匹配，返回空查询
                    return {"_id": {"$in": []}}
            else:
                # 权限查询中没有 _id 字段，保留基础查询的 _id
                base_query["_id"] = base_id_query
        
        # 合并基础查询和权限查询
        # 如果权限查询为空（只有 $or 且为空，或完全为空），直接返回基础查询
        if not permission_query or (permission_query == {}):
            return base_query
        
        # 如果基础查询中已经有 $or，需要合并
        if "$or" in base_query:
            # 将基础查询的 $or 和权限查询合并
            if "$and" not in base_query:
                base_query["$and"] = [{"$or": base_query.pop("$or")}]
            base_query["$and"].append(permission_query)
        elif "$and" in base_query:
            # 如果已经有 $and，直接添加权限查询
            base_query["$and"].append(permission_query)
        elif "$or" in permission_query:
            # 如果权限查询是 $or 结构，使用 $and 合并
            base_query = {
                "$and": [
                    base_query,
                    permission_query
                ]
            }
        else:
            # 检查是否有字段冲突（除了 _id 已经处理过）
            # 如果有冲突，使用 $and 合并
            has_conflict = any(key in base_query and key in permission_query 
                             for key in permission_query.keys() 
                             if key not in ["$or", "$and"])
            if has_conflict:
                # 使用 $and 合并基础查询和权限查询
                base_query = {
                    "$and": [
                        base_query,
                        permission_query
                    ]
                }
            else:
                # 没有冲突，直接合并字段
                base_query.update(permission_query)
        
        return base_query
    
    @staticmethod
    async def check_data_access(
        user: Dict[str, Any],
        db,
        data_item: Dict[str, Any],
        project_id_field: str = "project_id",
        assignee_id_field: Optional[str] = "assignee_id",
        reporter_id_field: Optional[str] = "reporter_id",
        creator_id_field: Optional[str] = "created_by",
        verifier_id_field: Optional[str] = None
    ) -> bool:
        """
        检查用户是否有权限访问特定数据项
        
        Args:
            user: 用户信息字典
            db: 数据库连接
            data_item: 数据项字典
            project_id_field: 项目ID字段名
            assignee_id_field: 负责人ID字段名
            reporter_id_field: 报告人ID字段名
            creator_id_field: 创建人ID字段名
            verifier_id_field: 验证人ID字段名（可选，用于缺陷等）
            
        Returns:
            bool: 如果用户有权限返回True，否则返回False
        """
        user_id = user.get("user_id")
        user_roles = user.get("roles", [])
        user_permissions = user.get("permissions", [])
        user_oid = ObjectId(user_id) if not isinstance(user_id, ObjectId) else user_id
        
        # 管理员拥有所有权限
        if "admin" in user_roles or "*" in user_permissions:
            return True
        
        # 检查是否为负责人
        if assignee_id_field and data_item.get(assignee_id_field):
            assignee_id = data_item[assignee_id_field]
            if assignee_id == user_oid or str(assignee_id) == user_id:
                return True
        
        # 检查是否为报告人
        if reporter_id_field and data_item.get(reporter_id_field):
            reporter_id = data_item[reporter_id_field]
            if reporter_id == user_oid or str(reporter_id) == user_id:
                return True
        
        # 检查是否为验证人
        if verifier_id_field and data_item.get(verifier_id_field):
            verifier_id = data_item[verifier_id_field]
            if verifier_id == user_oid or str(verifier_id) == user_id:
                return True
        
        # 检查是否为创建人
        if creator_id_field and data_item.get(creator_id_field):
            creator_id = data_item[creator_id_field]
            if creator_id == user_oid or str(creator_id) == user_id:
                return True
        
        # 检查项目访问权限
        if project_id_field and data_item.get(project_id_field):
            project_id = data_item[project_id_field]
            has_access = await PermissionService.check_project_access(
                str(project_id),
                user,
                db
            )
            if has_access:
                return True
        
        return False